package org.example.controller.platform;

import cn.dev33.satoken.annotation.SaCheckLogin;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.example.common.result.PageResult;
import org.example.common.result.Result;
import org.example.common.utils.SaTokenUtils;
import org.example.controller.dto.CreatePlatformUserRequest;
import org.example.entity.Role;
import org.example.entity.User;
import org.example.mapper.RoleMapper;
import org.example.service.PermissionService;
import org.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 平台端用户管理控制器
 * 管理平台管理员账号，不涉及租户概念
 */
@RestController
@RequestMapping("/platform/users")
@Slf4j
@Component("platformUserController")
@Tag(name = "平台端-用户管理", description = "平台端用户管理相关接口")
@SecurityRequirement(name = "platformBearerAuth")
public class UserController {

    @Autowired
    private UserService userService;
    
    @Autowired
    private PermissionService permissionService;
    
    @Autowired
    private RoleMapper roleMapper;
    
    @Autowired
    private org.example.mapper.UserRolePlatformRelationMapper userRolePlatformRelationMapper;

    @Autowired
    private SaTokenUtils saTokenUtils;

    /**
     * 分页查询平台用户列表
     */
    @SaCheckLogin
    @GetMapping
    @io.swagger.v3.oas.annotations.Operation(
        summary = "平台端-获取用户列表",
        description = "获取平台端用户列表，支持分页和搜索"
    )
    public Result<Map<String, Object>> getPlatformUserList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String username,
            @RequestParam(required = false) String phone,
            @RequestParam(required = false) String keyword) {
        try {
            // 验证当前用户是否为平台端
            String userType = saTokenUtils.getCurrentUserType();
            if (!"平台端".equals(userType)) {
                return Result.error("仅平台端用户可访问此接口");
            }
            
            // TODO: 从JWT Token获取当前用户ID，检查权限
            // Long currentUserId = getCurrentUserIdFromToken();
            // if (!permissionService.hasPermission(currentUserId, "system:user")) {
            //     return Result.forbidden("没有用户管理权限");
            // }
            
            // 兼容 keyword 模糊查询（姓名/手机号）
            if ((username == null || username.isBlank()) && (phone == null || phone.isBlank()) && keyword != null && !keyword.isBlank()) {
                username = keyword;
                phone = keyword;
            }

            PageResult<User> result = userService.getPlatformUserList(page, size, username, phone);

            // 组装前端需要的列表结构（平台端：从平台关联表取第一个角色作为展示）
            List<User> users = result.getRecords();
            List<Map<String, Object>> list = users.stream().map(u -> {
                Map<String, Object> item = new HashMap<>();
                item.put("id", u.getId());
                item.put("realName", u.getRealName());
                item.put("phone", u.getPhone());
                Long roleId = null; String roleName = null;
                try {
                    java.util.List<Long> roleIds = userRolePlatformRelationMapper.getRoleIdsByUserId(u.getId());
                    if (roleIds != null && !roleIds.isEmpty()) {
                        roleId = roleIds.get(0);
                        Role role = roleMapper.selectById(roleId);
                        roleName = role != null ? role.getRoleName() : null;
                    }
                } catch (Exception ignore) {}
                item.put("roleId", roleId);
                item.put("roleName", roleName);
                item.put("status", u.getStatus());  // 直接返回数字：0-禁用，1-启用
                item.put("statusText", u.getStatus() == null ? "未知" : (u.getStatus() == 1 ? "启用" : "禁用"));  // 添加可读的状态文本
                item.put("createdAt", u.getCreatedAt());
                return item;
            }).collect(Collectors.toList());

            Map<String, Object> data = new HashMap<>();
            data.put("total", result.getTotal());
            data.put("pageNum", result.getCurrent());
            data.put("pageSize", result.getSize());
            data.put("list", list);

            return Result.success(data);
        } catch (Exception e) {
            log.error("查询平台用户列表失败", e);
            return Result.error("查询平台用户列表失败");
        }
    }

    /**
     * 根据ID查询平台用户详情
     */
    @GetMapping("/{userId}")
    public Result<Map<String, Object>> getPlatformUserById(@PathVariable Long userId) {
        try {
            // TODO: 权限检查
            User user = userService.getPlatformUserById(userId);
            if (user == null) {
                return Result.notFound("用户不存在");
            }
            // 仅以平台关联表为准：取第一个 role_id，若无关联则为空
            Long effectiveRoleId = null; String roleName = null;
            try {
                java.util.List<Long> roleIds = userRolePlatformRelationMapper.getRoleIdsByUserId(userId);
                if (roleIds != null && !roleIds.isEmpty()) {
                    effectiveRoleId = roleIds.get(0);
                    Role role = roleMapper.selectById(effectiveRoleId);
                    if (role != null) roleName = role.getRoleName();
                }
            } catch (Exception ignore) {}

            Map<String, Object> data = new HashMap<>();
            data.put("id", user.getId());
            data.put("realName", user.getRealName());
            data.put("phone", user.getPhone());
            data.put("roleId", effectiveRoleId);
            data.put("roleName", roleName);
            data.put("avatarUrl", user.getAvatarUrl());
            return Result.success(data);
        } catch (Exception e) {
            log.error("查询平台用户详情失败: {}", userId, e);
            return Result.error("查询平台用户详情失败");
        }
    }

    /**
     * 创建平台管理员账号
     */
    @PostMapping
    public Result<Map<String, Object>> createPlatformUser(@RequestBody CreatePlatformUserRequest req) {
        try {
            // TODO: 权限检查
            if (req.getRealName() == null || req.getRealName().isBlank()) {
                return Result.badRequest("姓名不能为空");
            }
            if (req.getPhone() == null || req.getPhone().isBlank()) {
                return Result.badRequest("手机号不能为空");
            }
            if (req.getRoleId() == null) {
                return Result.badRequest("角色不能为空");
            }

            User user = new User();
            // username 若未提供，用手机号派生，避免唯一校验困难
            user.setUsername(req.getUsername() == null || req.getUsername().isBlank() ? req.getPhone() : req.getUsername());
            user.setRealName(req.getRealName());
            user.setPhone(req.getPhone());
            user.setAvatarUrl(req.getAvatarUrl());
            user.setPrimaryRoleId(req.getRoleId());
            user.setUserType("平台端");

            User createdUser = userService.createPlatformUser(user);
            // 同步平台端用户-角色关联：一个账号一个角色
            try {
                userRolePlatformRelationMapper.deleteByUserId(createdUser.getId());
                userRolePlatformRelationMapper.batchInsert(createdUser.getId(), List.of(req.getRoleId()));
            } catch (Exception ignore) {}

            Map<String, Object> data = new HashMap<>();
            data.put("id", createdUser.getId());
            return Result.success("创建成功", data);
        } catch (Exception e) {
            log.error("创建平台用户失败", e);
            return Result.error("创建失败: " + e.getMessage());
        }
    }

    /**
     * 更新平台用户信息
     */
    @PutMapping("/{userId}")
    public Result<User> updatePlatformUser(@PathVariable Long userId, @RequestBody java.util.Map<String, Object> body) {
        try {
            // TODO: 权限检查
            User userToUpdate = new User();
            userToUpdate.setId(userId);
            
            // 允许按需更新的字段
            if (body.containsKey("realName")) {
                Object v = body.get("realName");
                if (v instanceof String) userToUpdate.setRealName((String) v);
            }
            if (body.containsKey("phone")) {
                Object v = body.get("phone");
                if (v instanceof String) userToUpdate.setPhone((String) v);
            }
            if (body.containsKey("avatarUrl")) {
                Object v = body.get("avatarUrl");
                if (v instanceof String) userToUpdate.setAvatarUrl((String) v);
            }
            // 角色更新改为操作关联表
            Long newRoleId = null;
            if (body.containsKey("roleId")) {
                Object v = body.get("roleId");
                if (v instanceof Number) newRoleId = ((Number) v).longValue();
                else if (v instanceof String && !((String) v).isBlank()) { try { newRoleId = Long.parseLong((String) v); } catch (NumberFormatException ignore) {} }
            }
            // 可选：状态（0/1）
            if (body.containsKey("status")) {
                Object v = body.get("status");
                if (v instanceof Number) userToUpdate.setStatus(((Number) v).intValue());
                else if (v instanceof String && !((String) v).isBlank()) {
                    try { userToUpdate.setStatus(Integer.parseInt((String) v)); } catch (NumberFormatException ignore) {}
                }
            }
            
            User updatedUser = userService.updatePlatformUser(userToUpdate);
            if (newRoleId != null) {
                try {
                    userRolePlatformRelationMapper.deleteByUserId(userId);
                    userRolePlatformRelationMapper.batchInsert(userId, java.util.List.of(newRoleId));
                } catch (Exception ignore) {}
            }
            return Result.success("平台用户更新成功", updatedUser);
        } catch (Exception e) {
            log.error("更新平台用户失败: {}", userId, e);
            return Result.error("更新平台用户失败: " + e.getMessage());
        }
    }

    /**
     * 删除平台用户
     */
    @DeleteMapping("/{userId}")
    public Result<String> deletePlatformUser(@PathVariable Long userId) {
        try {
            // TODO: 权限检查
            userService.deletePlatformUser(userId);
            return Result.success("平台用户删除成功");
        } catch (Exception e) {
            log.error("删除平台用户失败: {}", userId, e);
            return Result.error("删除平台用户失败");
        }
    }

    /**
     * 获取平台用户角色列表
     */
    @GetMapping("/{userId}/roles")
    public Result<List<Role>> getPlatformUserRoles(@PathVariable Long userId) {
        try {
            // TODO: 权限检查
            List<Role> roles = permissionService.getPlatformRolesByUserId(userId);
            return Result.success(roles);
        } catch (Exception e) {
            log.error("获取平台用户角色失败: {}", userId, e);
            return Result.error("获取平台用户角色失败");
        }
    }

    /**
     * 为平台用户分配角色
     */
    @PostMapping("/{userId}/roles")
    public Result<String> assignPlatformRoles(@PathVariable Long userId, @RequestBody List<Long> roleIds) {
        try {
            // TODO: 权限检查
            userService.assignPlatformRoles(userId, roleIds);
            return Result.success("角色分配成功");
        } catch (Exception e) {
            log.error("分配平台用户角色失败: {} -> {}", userId, roleIds, e);
            return Result.error("分配角色失败: " + e.getMessage());
        }
    }

    /**
     * 获取平台用户权限列表
     */
    @GetMapping("/{userId}/permissions")
    public Result<List<String>> getPlatformUserPermissions(@PathVariable Long userId) {
        try {
            // TODO: 权限检查
            List<String> permissions = permissionService.getPlatformPermissionsByUserId(userId);
            return Result.success(permissions);
        } catch (Exception e) {
            log.error("获取平台用户权限失败: {}", userId, e);
            return Result.error("获取平台用户权限失败");
        }
    }

    /**
     * 启用/禁用平台用户
     */
    @PatchMapping("/{userId}/status")
    public Result<String> updatePlatformUserStatus(@PathVariable Long userId, @RequestParam Integer status) {
        try {
            // TODO: 权限检查
            // status: 0-禁用，1-启用
            if (status == null || (status != 0 && status != 1)) {
                return Result.badRequest("状态参数无效，请使用0(禁用)或1(启用)");
            }
            
            userService.updatePlatformUserStatus(userId, status);
            String message = status == 1 ? "平台用户启用成功" : "平台用户禁用成功";
            return Result.success(message);
        } catch (Exception e) {
            log.error("更新平台用户状态失败: {} -> {}", userId, status, e);
            return Result.error("更新平台用户状态失败: " + e.getMessage());
        }
    }

    /**
     * 重置平台用户密码
     */
    @PostMapping("/{userId}/reset-password")
    public Result<String> resetPlatformUserPassword(@PathVariable Long userId) {
        try {
            // TODO: 权限检查
            userService.resetPlatformUserPassword(userId);
            return Result.success("密码重置成功");
        } catch (Exception e) {
            log.error("重置平台用户密码失败: {}", userId, e);
            return Result.error("重置密码失败");
        }
    }

    
}
